﻿using IdentityExample.Data;
using IdentityExample.Data.Models;
using IdentityExample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IdentityExample.Adapters.Data
{
    public class MovieDataAdapter : IMovieAdapter
    {
        public FavoriteMoviesViewModel GetFavoriteMoviesViewModel(string userId)
        {
            FavoriteMoviesViewModel model = null;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model = db.Users.Where(u => u.Id == userId).Select(u => new FavoriteMoviesViewModel
                {
                    UserId = userId,
                    UserName = u.UserName,
                    Movies = u.UserMovies.Select(um => new MovieViewModel
                    {
                        MovieId = um.MovieId,
                        RatingId = um.RatingId,
                        RatingName = um.Rating.Name,
                        Title = um.Movie.Title
                    }).ToList()
                    
                }).FirstOrDefault();
            }

            return model;
        }

        public void CreateUserMovie(CreateUserMovieViewModel model)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                UserMovie um = new UserMovie();
                um.MovieId = model.SelectedMovieId;
                um.RatingId = model.SelectedRatingId;
                um.UserId = model.UserId;

                db.UsersMovies.Add(um);
                db.SaveChanges();
            }
        }

        public void HydrateLookups(CreateUserMovieViewModel model)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model.Movies = db.Movies.Select(m => new MovieSelectViewModel
                {
                    MovieId = m.MovieId,
                    Title = m.Title
                }).ToList();

                model.Ratings = db.Ratings.Select(r => new RatingSelectViewModel
                {
                    RatingId = r.RatingId,
                    Name = r.Name
                }).ToList();
            }
        }
    }
}